Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
google-auth-library
Advanced tools
The google-auth-library npm package is a comprehensive library for OAuth2 and Google Sign-in authentication for Node.js applications. It provides easy-to-use methods to authenticate users, obtain access tokens, and interact with Google APIs.
OAuth2 Client
This feature allows you to create an OAuth2 client, generate an authentication URL, and exchange an authorization code for an access token.
const { OAuth2Client } = require('google-auth-library');
const oAuth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
// Generate an authentication URL
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/drive']
});
// Exchange authorization code for access token
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
});
Google Sign-in
This feature allows you to verify the Google ID token for Google Sign-in and retrieve user information from the payload.
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID
});
const payload = ticket.getPayload();
const userid = payload['sub'];
}
verify().catch(console.error);
Application Default Credentials
This feature allows you to authenticate using the default credentials that Google provides for applications running on Google Cloud Platform or elsewhere.
const { google } = require('google-auth-library');
async function main() {
const auth = new google.auth.GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}
main().catch(console.error);
This package is a strategy for Passport.js that allows you to authenticate users using Google OAuth 2.0. It is similar to google-auth-library in that it provides OAuth2 functionality, but it is specifically designed to work within the Passport.js middleware pattern.
node-oauth2-server is a library that allows you to implement an OAuth2 server in Node.js applications. It differs from google-auth-library as it is not specific to Google's OAuth2 implementation and can be used to create a custom OAuth2 service.
This is Google's officially supported node.js client library for using OAuth 2.0 authorization and authentication with Google APIs.
A comprehensive list of changes in each version may be found in the CHANGELOG.
Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.
Table of contents:
npm install google-auth-library
This library provides a variety of ways to authenticate to your Google services.
This library provides an implementation of Application Default Credentialsfor Node.js. The Application Default Credentials provide a simple way to get authorization credentials for use in calling Google APIs.
They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform.
Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: Workload Identity Federation.
To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to APIs & Auth > Credentials in the Google Developers Console and select Service account from the Add credentials dropdown.
This file is your only copy of these credentials. It should never be committed with your source code, and should be stored securely.
Once downloaded, store the path to this file in the GOOGLE_APPLICATION_CREDENTIALS
environment variable.
Before making your API call, you must be sure the API you're calling has been enabled. Go to APIs & Auth > APIs in the Google Developers Console and enable the APIs you'd like to call. For the example below, you must enable the DNS API
.
Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under.
For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array to the GoogleAuth
constructor.
The code below shows how to retrieve a default credential type, depending upon the runtime environment.
const {GoogleAuth} = require('google-auth-library');
/**
* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
* this library will automatically choose the right client based on the environment.
*/
async function main() {
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}
main().catch(console.error);
This library comes with an OAuth2 client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an expiry_date
and the token is expired. The basics of Google's OAuth2 implementation is explained on Google Authorization and Authentication documentation.
In the following examples, you may need a CLIENT_ID
, CLIENT_SECRET
and REDIRECT_URL
. You can find these pieces of information by going to the Developer Console, clicking your project > APIs & auth > credentials.
For more information about OAuth2 and how it works, see here.
Let's take a look at a complete example.
const {OAuth2Client} = require('google-auth-library');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');
// Download your OAuth2 configuration from the Google
const keys = require('./oauth2.keys.json');
/**
* Start by acquiring a pre-authenticated oAuth2 client.
*/
async function main() {
const oAuth2Client = await getAuthenticatedClient();
// Make a simple request to the People API using our pre-authenticated client. The `request()` method
// takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios.
const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
const res = await oAuth2Client.request({url});
console.log(res.data);
// After acquiring an access_token, you may want to check on the audience, expiration,
// or original scopes requested. You can do that with the `getTokenInfo` method.
const tokenInfo = await oAuth2Client.getTokenInfo(
oAuth2Client.credentials.access_token
);
console.log(tokenInfo);
}
/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow. Return the full client to the callback.
*/
function getAuthenticatedClient() {
return new Promise((resolve, reject) => {
// create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file,
// which should be downloaded from the Google Developers Console.
const oAuth2Client = new OAuth2Client(
keys.web.client_id,
keys.web.client_secret,
keys.web.redirect_uris[0]
);
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/userinfo.profile',
});
// Open an http server to accept the oauth callback. In this simple example, the
// only request to our webserver is to /oauth2callback?code=<code>
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
// acquire the code from the querystring, and close the web server.
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
const code = qs.get('code');
console.log(`Code is ${code}`);
res.end('Authentication successful! Please return to the console.');
server.destroy();
// Now that we have the code, use that to acquire tokens.
const r = await oAuth2Client.getToken(code);
// Make sure to set the credentials on the OAuth2 client.
oAuth2Client.setCredentials(r.tokens);
console.info('Tokens acquired.');
resolve(oAuth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// open the browser to the authorize url to start the workflow
open(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}
main().catch(console.error);
This library will automatically obtain an access_token
, and automatically refresh the access_token
if a refresh_token
is present. The refresh_token
is only returned on the first authorization, so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the tokens
event:
const client = await auth.getClient();
client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
// The `tokens` event would now be raised if this was the first request
With the code returned, you can ask for an access token as shown below:
const tokens = await oauth2Client.getToken(code);
// Now tokens contains an access_token and an optional refresh_token. Save them.
oauth2Client.setCredentials(tokens);
If you need to obtain a new refresh_token
, ensure the call to generateAuthUrl
sets the access_type
to offline
. The refresh token will only be returned for the first authorization by the user. To force consent, set the prompt
property to consent
:
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
// To get a refresh token, you MUST set access_type to `offline`.
access_type: 'offline',
// set the appropriate scopes
scope: 'https://www.googleapis.com/auth/userinfo.profile',
// A refresh token is only returned the first time the user
// consents to providing access. For illustration purposes,
// setting the prompt to 'consent' will force this consent
// every time, forcing a refresh_token to be returned.
prompt: 'consent'
});
access_token
informationAfter obtaining and storing an access_token
, at a later time you may want to go check the expiration date,
original scopes, or audience for the token. To get the token info, you can use the getTokenInfo
method:
// after acquiring an oAuth2Client...
const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token');
// take a look at the scopes originally provisioned for the access token
console.log(tokenInfo.scopes);
This method will throw if the token is invalid.
If you're authenticating with OAuth2 from an installed application (like Electron), you may not want to embed your client_secret
inside of the application sources. To work around this restriction, you can choose the iOS
application type when creating your OAuth2 credentials in the Google Developers console:
If using the iOS
type, when creating the OAuth2 client you won't need to pass a client_secret
into the constructor:
const oAuth2Client = new OAuth2Client({
clientId: <your_client_id>,
redirectUri: <your_redirect_uri>
});
The Google Developers Console provides a .json
file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account.
const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');
async function main() {
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);
The parameters for the JWT auth client including how to use it with a .pem
file are explained in samples/jwt.js.
Instead of loading credentials from a key file, you can also provide them using an environment variable and the GoogleAuth.fromJSON()
method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc).
Start by exporting your credentials:
$ export CREDS='{
"type": "service_account",
"project_id": "your-project-id",
"private_key_id": "your-private-key-id",
"private_key": "your-private-key",
"client_email": "your-client-email",
"client_id": "your-client-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "your-cert-url"
}'
Now you can create a new client from the credentials:
const {auth} = require('google-auth-library');
// load the environment variable with our keys
const keysEnvVar = process.env['CREDS'];
if (!keysEnvVar) {
throw new Error('The $CREDS environment variable was not found!');
}
const keys = JSON.parse(keysEnvVar);
async function main() {
// load the JWT or UserRefreshClient from the keys
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);
You can set the HTTPS_PROXY
or https_proxy
environment variables to proxy HTTPS requests. When HTTPS_PROXY
or https_proxy
are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present.
If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account.
Note: In most cases, you will want to use Application Default Credentials. Direct use of the Compute
class is for very specific scenarios.
const {auth, Compute} = require('google-auth-library');
async function main() {
const client = new Compute({
// Specifying the service account email is optional.
serviceAccountEmail: 'my-service-account@example.com'
});
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);
Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).
Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.
In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:
Follow the detailed instructions on how to configure workload identity federation from AWS.
After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.
To generate the AWS workload identity configuration, run the following command:
# Generate an AWS configuration file.
gcloud iam workload-identity-pools create-cred-config \
projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \
--service-account $SERVICE_ACCOUNT_EMAIL \
--aws \
--output-file /path/to/generated/config.json
Where the following variables need to be substituted:
$PROJECT_NUMBER
: The Google Cloud project number.$POOL_ID
: The workload identity pool ID.$AWS_PROVIDER_ID
: The AWS provider ID.$SERVICE_ACCOUNT_EMAIL
: The email of the service account to impersonate.This will generate the configuration file in the specified output file.
If you want to use the AWS IMDSv2 flow, you can add the field below to the credential_source in your AWS ADC configuration file: "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" The gcloud create-cred-config command will be updated to support this soon.
You can now start using the Auth library to call Google Cloud resources from AWS.
In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed:
Follow the detailed instructions on how to configure workload identity federation from Microsoft Azure.
After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.
To generate the Azure workload identity configuration, run the following command:
# Generate an Azure configuration file.
gcloud iam workload-identity-pools create-cred-config \
projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \
--service-account $SERVICE_ACCOUNT_EMAIL \
--azure \
--output-file /path/to/generated/config.json
Where the following variables need to be substituted:
$PROJECT_NUMBER
: The Google Cloud project number.$POOL_ID
: The workload identity pool ID.$AZURE_PROVIDER_ID
: The Azure provider ID.$SERVICE_ACCOUNT_EMAIL
: The email of the service account to impersonate.This will generate the configuration file in the specified output file.
You can now start using the Auth library to call Google Cloud resources from Azure.
In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:
Follow the detailed instructions on how to configure workload identity federation from an OIDC identity provider.
After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.
For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials).
File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.
To generate a file-sourced OIDC configuration, run the following command:
# Generate an OIDC configuration file for file-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
--service-account $SERVICE_ACCOUNT_EMAIL \
--credential-source-file $PATH_TO_OIDC_ID_TOKEN \
# Optional arguments for file types. Default is "text":
# --credential-source-type "json" \
# Optional argument for the field that contains the OIDC credential.
# This is required for json.
# --credential-source-field-name "id_token" \
--output-file /path/to/generated/config.json
Where the following variables need to be substituted:
$PROJECT_NUMBER
: The Google Cloud project number.$POOL_ID
: The workload identity pool ID.$OIDC_PROVIDER_ID
: The OIDC provider ID.$SERVICE_ACCOUNT_EMAIL
: The email of the service account to impersonate.$PATH_TO_OIDC_ID_TOKEN
: The file path where the OIDC token will be retrieved from.This will generate the configuration file in the specified output file.
URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.
To generate a URL-sourced OIDC workload identity configuration, run the following command:
# Generate an OIDC configuration file for URL-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
--service-account $SERVICE_ACCOUNT_EMAIL \
--credential-source-url $URL_TO_GET_OIDC_TOKEN \
--credential-source-headers $HEADER_KEY=$HEADER_VALUE \
# Optional arguments for file types. Default is "text":
# --credential-source-type "json" \
# Optional argument for the field that contains the OIDC credential.
# This is required for json.
# --credential-source-field-name "id_token" \
--output-file /path/to/generated/config.json
Where the following variables need to be substituted:
$PROJECT_NUMBER
: The Google Cloud project number.$POOL_ID
: The workload identity pool ID.$OIDC_PROVIDER_ID
: The OIDC provider ID.$SERVICE_ACCOUNT_EMAIL
: The email of the service account to impersonate.$URL_TO_GET_OIDC_TOKEN
: The URL of the local server endpoint to call to retrieve the OIDC token.$HEADER_KEY
and $HEADER_VALUE
: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN
, e.g. Metadata-Flavor=Google
.You can now start using the Auth library to call Google Cloud resources from an OIDC provider.
External identities (AWS, Azure and OIDC-based providers) can be used with Application Default Credentials
.
In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above.
Once generated, store the path to this file in the GOOGLE_APPLICATION_CREDENTIALS
environment variable.
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json
The library can now automatically choose the right type of client and initialize credentials from the context provided in the configuration file.
async function main() {
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}
When using external identities with Application Default Credentials in Node.js, the roles/browser
role needs to be granted to the service account.
The Cloud Resource Manager API
should also be enabled on the project.
This is needed since the library will try to auto-discover the project ID from the current environment using the impersonated credential.
To avoid this requirement, the project ID can be explicitly specified on initialization.
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
// Pass the project ID explicitly to avoid the need to grant `roles/browser` to the service account
// or enable Cloud Resource Manager API on the project.
projectId: 'CLOUD_RESOURCE_PROJECT_ID',
});
You can also explicitly initialize external account clients using the generated configuration file.
const {ExternalAccountClient} = require('google-auth-library');
const jsonConfig = require('/path/to/config.json');
async function main() {
const client = ExternalAccountClient.fromJSON(jsonConfig);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.request({url});
console.log(res.data);
}
If your application is running on Cloud Run or Cloud Functions, or using Cloud Identity-Aware
Proxy (IAP), you will need to fetch an ID token to access your application. For
this, use the method getIdTokenClient
on the GoogleAuth
client.
For invoking Cloud Run services, your service account will need the
Cloud Run Invoker
IAM permission.
For invoking Cloud Functions, your service account will need the
Function Invoker
IAM permission.
// Make a request to a protected Cloud Run service.
const {GoogleAuth} = require('google-auth-library');
async function main() {
const url = 'https://cloud-run-1234-uc.a.run.app';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(url);
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);
A complete example can be found in samples/idtokens-serverless.js
.
For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID used when you set up your protected resource as the target audience.
// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource
const {GoogleAuth} = require('google-auth-library');
async function main()
const targetAudience = 'iap-client-id';
const url = 'https://iap-url.com';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(targetAudience);
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);
A complete example can be found in samples/idtokens-iap.js
.
If you've secured your IAP app with signed headers, you can use this library to verify the IAP header:
const {OAuth2Client} = require('google-auth-library');
// Expected audience for App Engine.
const expectedAudience = `/projects/your-project-number/apps/your-project-id`;
// IAP issuer
const issuers = ['https://cloud.google.com/iap'];
// Verify the token. OAuth2Client throws an Error if verification fails
const oAuth2Client = new OAuth2Client();
const response = await oAuth2Client.getIapCerts();
const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
idToken,
response.pubkeys,
expectedAudience,
issuers
);
// Print out the info contained in the IAP ID token
console.log(ticket)
A complete example can be found in samples/verifyIdToken-iap.js
.
Google Cloud Impersonated credentials used for Creating short-lived service account credentials.
Provides authentication for applications where local credentials impersonates a remote service account using IAM Credentials API.
An Impersonated Credentials Client is instantiated with a sourceClient
. This
client should use credentials that have the "Service Account Token Creator" role (roles/iam.serviceAccountTokenCreator
),
and should authenticate with the https://www.googleapis.com/auth/cloud-platform
, or https://www.googleapis.com/auth/iam
scopes.
sourceClient
is used by the Impersonated
Credentials Client to impersonate a target service account with a specified
set of scopes.
const { GoogleAuth, Impersonated } = require('google-auth-library');
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
async function main() {
// Acquire source credentials:
const auth = new GoogleAuth();
const client = await auth.getClient();
// Impersonate new credentials:
let targetClient = new Impersonated({
sourceClient: client,
targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform']
});
// Get impersonated credentials:
const authHeaders = await targetClient.getRequestHeaders();
// Do something with `authHeaders.Authorization`.
// Use impersonated credentials:
const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID'
const resp = await targetClient.request({ url });
for (const bucket of resp.data.items) {
console.log(bucket.name);
}
// Use impersonated credentials with google-cloud client library
// Note: this works only with certain cloud client libraries utilizing gRPC
// e.g., SecretManager, KMS, AIPlatform
// will not currently work with libraries using REST, e.g., Storage, Compute
const smClient = new SecretManagerServiceClient({
projectId: anotherProjectID,
auth: {
getClient: () => targetClient,
},
});
const secretName = 'projects/anotherProjectNumber/secrets/someProjectName/versions/1';
const [accessResponse] = await smClient.accessSecretVersion({
name: secretName,
});
const responsePayload = accessResponse.payload.data.toString('utf8');
// Do something with the secret contained in `responsePayload`.
};
main();
Downscoping with Credential Access Boundaries is used to restrict the Identity and Access Management (IAM) permissions that a short-lived credential can use.
The DownscopedClient
class can be used to produce a downscoped access token from a
CredentialAccessBoundary
and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges, e.g. Principle of Least Privilege.
Notice: Only Cloud Storage supports Credential Access Boundaries for now.
There are two entities needed to generate and use credentials generated from Downscoped Client with Credential Access Boundaries.
const {GoogleAuth, DownscopedClient} = require('google-auth-library');
// Define CAB rules which will restrict the downscoped token to have readonly
// access to objects starting with "customer-a" in bucket "bucket_name".
const cabRules = {
accessBoundary: {
accessBoundaryRules: [
{
availableResource: `//storage.googleapis.com/projects/_/buckets/bucket_name`,
availablePermissions: ['inRole:roles/storage.objectViewer'],
availabilityCondition: {
expression:
`resource.name.startsWith('projects/_/buckets/` +
`bucket_name/objects/customer-a)`
}
},
],
},
};
// This will use ADC to get the credentials used for the downscoped client.
const googleAuth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
// Obtain an authenticated client via ADC.
const client = await googleAuth.getClient();
// Use the client to create a DownscopedClient.
const cabClient = new DownscopedClient(client, cab);
// Refresh the tokens.
const refreshedAccessToken = await cabClient.getAccessToken();
// This will need to be passed to the token consumer.
access_token = refreshedAccessToken.token;
expiry_date = refreshedAccessToken.expirationTime;
A token broker can be set up on a server in a private network. Various workloads (token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets.
The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer.
const {OAuth2Client} = require('google-auth-library');
const {Storage} = require('@google-cloud/storage');
// Create the OAuth credentials (the consumer).
const oauth2Client = new OAuth2Client();
// We are defining a refresh handler instead of a one-time access
// token/expiry pair.
// This will allow the consumer to obtain new downscoped tokens on
// demand every time a token is expired, without any additional code
// changes.
oauth2Client.refreshHandler = async () => {
// The common pattern of usage is to have a token broker pass the
// downscoped short-lived access tokens to a token consumer via some
// secure authenticated channel.
const refreshedAccessToken = await cabClient.getAccessToken();
return {
access_token: refreshedAccessToken.token,
expiry_date: refreshedAccessToken.expirationTime,
}
};
// Use the consumer client to define storageOptions and create a GCS object.
const storageOptions = {
projectId: 'my_project_id',
authClient: oauth2Client,
};
const storage = new Storage(storageOptions);
const downloadFile = await storage
.bucket('bucket_name')
.file('customer-a-data.txt')
.download();
console.log(downloadFile.toString('utf8'));
main().catch(console.error);
Samples are in the samples/
directory. Each sample's README.md
has instructions for running its sample.
Sample | Source Code | Try it |
---|---|---|
Adc | source code | |
Compute | source code | |
Credentials | source code | |
Downscopedclient | source code | |
Headers | source code | |
ID Tokens for Identity-Aware Proxy (IAP) | source code | |
ID Tokens for Serverless | source code | |
Jwt | source code | |
Keepalive | source code | |
Keyfile | source code | |
Oauth2-code Verifier | source code | |
Oauth2 | source code | |
Sign Blob | source code | |
Verifying ID Tokens from Identity-Aware Proxy (IAP) | source code | |
Verify Id Token | source code |
The Google Auth Library Node.js Client API Reference documentation also contains samples.
Our client libraries follow the Node.js release schedule. Libraries are compatible with all current active and maintenance versions of Node.js. If you are using an end-of-life version of Node.js, we recommend that you update as soon as possible to an actively supported LTS version.
Google's client libraries support legacy versions of Node.js runtimes on a best-efforts basis with the following warnings:
Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm dist-tags.
The dist-tags follow the naming convention legacy-(version)
.
For example, npm install google-auth-library@legacy-8
installs client libraries
for versions compatible with Node.js 8.
This library follows Semantic Versioning.
This library is considered to be stable. The code surface will not change in backwards-incompatible ways unless absolutely necessary (e.g. because of critical security issues) or with an extensive deprecation period. Issues and requests against stable libraries are addressed with the highest priority.
More Information: Google Cloud Platform Launch Stages
Contributions welcome! See the Contributing Guide.
Please note that this README.md
, the samples/README.md
,
and a variety of configuration files in this repository (including .nycrc
and tsconfig.json
)
are generated from a central template. To edit one of these files, make an edit
to its templates in
directory.
Apache Version 2.0
See LICENSE
FAQs
Google APIs Authentication Client Library for Node.js
The npm package google-auth-library receives a total of 7,126,341 weekly downloads. As such, google-auth-library popularity was classified as popular.
We found that google-auth-library demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.